package com.sse.product.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sse.product.rbac.entity.User;
import com.sse.product.rbac.entity.UserRole;
import com.sse.product.rbac.mapper.UserRoleMapper;
import com.sse.product.rbac.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author junyongli
 * @since 2022-07-22
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public List<Long> queryRoleIdByUser(User user) {
        List<UserRole> list = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        return list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Integer deleteRoleByUser(User user) {
        return userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId,user.getId()));
    }

    @Override
    @Transactional
    public boolean addRolesByUser(Long userId, List<Long> roleIdList) {
        List<UserRole> userRoleList=new ArrayList<>();
        roleIdList.forEach(roleId->userRoleList.add(new UserRole(userId,roleId)));
        return this.saveBatch(userRoleList);
    }
}
